<?php
session_start();
// 验证管理员权限
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: login.php');
    exit;
}

// 数据库配置
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';

$categories = []; // 分类列表
$error = '';
$success = '';
$currentCategory = []; // 编辑时的分类数据
$hasCreateTime = true; // 标记表中是否有create_time字段（默认假设没有，避免错误）

try {
    // 建立数据库连接
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );

    // 检查categories表是否有create_time字段（关键修复）
    try {
        $stmt = $pdo->query("DESCRIBE categories create_time");
        $field = $stmt->fetch();
        $hasCreateTime = !empty($field); // 存在则为true
    } catch (PDOException $e) {
        $hasCreateTime = false; // 不存在则为false
    }

    // 1. 获取所有分类（根据是否有create_time字段调整查询）
    $sql = $hasCreateTime 
        ? "SELECT id, name, sort_order, create_time FROM categories ORDER BY sort_order ASC" 
        : "SELECT id, name, sort_order FROM categories ORDER BY sort_order ASC";
    $stmt = $pdo->query($sql);
    if ($stmt !== false) {
        $categories = $stmt->fetchAll();
    } else {
        throw new Exception("分类列表查询失败，请检查表是否存在");
    }

    // 2. 处理新增/编辑提交
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $name = trim($_POST['name'] ?? '');
        $sortOrder = isset($_POST['sort_order']) ? (int)$_POST['sort_order'] : 0;
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

        if (empty($name)) {
            $error = "分类名称不能为空";
        } else {
            try {
                if ($id > 0) {
                    // 编辑分类（无需修改create_time）
                    $stmt = $pdo->prepare("UPDATE categories SET 
                        name = :name, 
                        sort_order = :sort_order 
                        WHERE id = :id");
                    $stmt->execute([
                        ':name' => $name,
                        ':sort_order' => $sortOrder,
                        ':id' => $id
                    ]);
                    $success = "分类更新成功";
                } else {
                    // 新增分类（根据是否有create_time字段调整SQL）
                    if ($hasCreateTime) {
                        $stmt = $pdo->prepare("INSERT INTO categories (name, sort_order, create_time) 
                            VALUES (:name, :sort_order, NOW())");
                        $stmt->execute([
                            ':name' => $name,
                            ':sort_order' => $sortOrder
                        ]);
                    } else {
                        // 表中没有create_time字段，不插入该字段
                        $stmt = $pdo->prepare("INSERT INTO categories (name, sort_order) 
                            VALUES (:name, :sort_order)");
                        $stmt->execute([
                            ':name' => $name,
                            ':sort_order' => $sortOrder
                        ]);
                    }
                    $success = "分类添加成功";
                }
                header('Location: category.php?success=' . urlencode($success));
                exit;
            } catch (PDOException $e) {
                $error = "操作失败：" . $e->getMessage();
            }
        }
    }

    // 3. 编辑时获取分类数据
    if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
        $id = (int)$_GET['edit'];
        $sql = $hasCreateTime 
            ? "SELECT id, name, sort_order, create_time FROM categories WHERE id = :id" 
            : "SELECT id, name, sort_order FROM categories WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $currentCategory = $stmt->fetch() ?: [];
    }

    // 4. 删除分类（检查关联文章）
    if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
        $id = (int)$_GET['delete'];
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM article WHERE category_id = :id");
        $stmt->execute([':id' => $id]);
        $count = $stmt->fetch()['count'];
        if ($count > 0) {
            $error = "该分类下有关联文章，无法删除";
        } else {
            $stmt = $pdo->prepare("DELETE FROM categories WHERE id = :id");
            $stmt->execute([':id' => $id]);
            header('Location: category.php?success=分类已删除');
            exit;
        }
    }

} catch (PDOException $e) {
    $error = "数据库连接失败：" . $e->getMessage();
} catch (Exception $e) {
    $error = $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分类管理 - 知识库管理系统</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/common.css">
    <style>
        .form-card.hidden { display: none; }
        .form-card { margin-bottom: 1.5rem; }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- 侧边栏 -->
        <aside class="admin-sidebar">
            <div class="sidebar-logo">
                <i class="fas fa-cogs"></i>
                <span>知识库管理</span>
            </div>
            <ul class="nav-list">
                <li class="nav-item"><a href="index.php" class="nav-link"><i class="fas fa-home"></i><span>管理首页</span></a></li>
                <li class="nav-item"><a href="article.php" class="nav-link"><i class="fas fa-file-alt"></i><span>文章管理</span></a></li>
                <li class="nav-item"><a href="category.php" class="nav-link active"><i class="fas fa-folder"></i><span>分类管理</span></a></li>
                <li class="nav-item"><a href="version.php" class="nav-link"><i class="fas fa-sync-alt"></i><span>版本管理</span></a></li>
                <li class="nav-item"><a href="user.php" class="nav-link"><i class="fas fa-users"></i><span>用户管理</span></a></li>
                <li class="nav-item"><a href="logout.php" class="nav-link"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></a></li>
            </ul>
        </aside>

        <!-- 主内容区 -->
        <main class="admin-content">
            <div class="content-wrapper">
                <div class="page-header">
                    <h1 class="page-title">分类管理</h1>
                    <button class="btn btn-primary" onclick="showForm('新增分类', 0)">
                        <i class="fas fa-plus"></i> 新增分类
                    </button>
                </div>

                <!-- 提示信息 -->
                <?php if (isset($_GET['success'])): ?>
                    <div class="message message-success"><i class="fas fa-check-circle"></i><?php echo htmlspecialchars($_GET['success']); ?></div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="message message-error"><i class="fas fa-exclamation-circle"></i><?php echo htmlspecialchars($error); ?></div>
                <?php endif; ?>

                <!-- 分类表单（默认隐藏） -->
                <div class="form-card hidden" id="categoryFormCard">
                    <h3 id="formTitle">新增分类</h3>
                    <form method="POST" action="" id="categoryForm">
                        <input type="hidden" name="id" id="formId" value="0">
                        
                        <div class="form-group">
                            <label class="form-label" for="name">分类名称 <span style="color: #EF4444;">*</span></label>
                            <input type="text" id="name" name="name" class="form-control" placeholder="请输入分类名称">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label" for="sort_order">排序序号</label>
                            <input type="number" id="sort_order" name="sort_order" class="form-control" value="0" 
                                placeholder="数字越小越靠前">
                        </div>
                        
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">保存</button>
                            <button type="button" class="btn btn-outline" onclick="hideForm()">取消</button>
                        </div>
                    </form>
                </div>

                <!-- 分类列表 -->
                <div class="form-card">
                    <h3>分类记录列表</h3>
                    <div style="overflow-x: auto; margin-top: 1rem;">
                        <table style="width:100%; border-collapse:collapse;">
                            <thead>
                                <tr style="background:#F1F5F9; border-bottom:1px solid #E2E8F0;">
                                    <th style="padding:0.75rem; text-align:left; width:5%;">ID</th>
                                    <th style="padding:0.75rem; text-align:left; width:30%;">分类名称</th>
                                    <th style="padding:0.75rem; text-align:left; width:15%;">排序序号</th>
                                    <?php if ($hasCreateTime): ?>
                                        <th style="padding:0.75rem; text-align:left; width:25%;">创建时间</th>
                                    <?php endif; ?>
                                    <th style="padding:0.75rem; text-align:left; width:<?php echo $hasCreateTime ? '25%' : '45%;'; ?>">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($categories as $c): ?>
                                    <tr style="border-bottom:1px solid #E2E8F0;">
                                        <td style="padding:0.75rem;"><?php echo $c['id']; ?></td>
                                        <td style="padding:0.75rem;"><?php echo htmlspecialchars($c['name']); ?></td>
                                        <td style="padding:0.75rem;"><?php echo $c['sort_order']; ?></td>
                                        <?php if ($hasCreateTime): ?>
                                            <td style="padding:0.75rem;"><?php echo $c['create_time'] ?? '无记录'; ?></td>
                                        <?php endif; ?>
                                        <td style="padding:0.75rem;">
                                            <a href="javascript:;" class="btn btn-sm btn-outline" 
                                               onclick="showForm('编辑分类', <?php echo $c['id']; ?>, 
                                               '<?php echo htmlspecialchars($c['name']); ?>', <?php echo $c['sort_order']; ?>)">
                                                编辑
                                            </a>
                                            <a href="category.php?delete=<?php echo $c['id']; ?>" class="btn btn-sm btn-danger" 
                                               onclick="return confirm('确定删除该分类吗？')">删除</a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (empty($categories)): ?>
                                    <tr>
                                        <td colspan="<?php echo $hasCreateTime ? 5 : 4; ?>" style="padding:2rem; text-align:center; color:#64748B;">暂无分类记录</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // 显示表单（新增/编辑）
        function showForm(title, id, name = '', sortOrder = 0) {
            document.getElementById('formTitle').textContent = title;
            document.getElementById('formId').value = id;
            document.getElementById('name').value = name;
            document.getElementById('sort_order').value = sortOrder;
            document.getElementById('categoryFormCard').classList.remove('hidden');
        }

        // 隐藏表单
        function hideForm() {
            document.getElementById('categoryFormCard').classList.add('hidden');
        }

        // 编辑或错误时自动显示表单
        <?php if (!empty($currentCategory) || $error): ?>
            window.onload = function() {
                <?php if (!empty($currentCategory)): ?>
                    showForm('编辑分类', 
                        <?php echo $currentCategory['id']; ?>, 
                        '<?php echo htmlspecialchars($currentCategory['name']); ?>', 
                        <?php echo $currentCategory['sort_order']; ?>
                    );
                <?php else: ?>
                    document.getElementById('categoryFormCard').classList.remove('hidden');
                <?php endif; ?>
            };
        <?php endif; ?>
    </script>
</body>
</html>